package com.lamer.console.blog.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lamer.console.blog.entity.Category;
import com.lamer.console.blog.service.ICategoryService;
import com.lamer.console.common.api.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 黄诗鹏
 * @since 2021-09-25
 */
@RestController
@RequestMapping("/blog")
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    @GetMapping("/category/page/")
    public ApiResult<Page<Category>> getPage(@RequestParam("search") String search) {
        JSONObject jsonObject = JSON.parseObject(search);
        Integer number = jsonObject.getInteger("page_number");
        Integer size = jsonObject.getInteger("page_size");
        String categoryName = jsonObject.getString("categoryName");

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(categoryName)) queryWrapper.like(Category::getCategoryName, categoryName);

        Page<Category> page = categoryService.page(new Page<>(number, size), queryWrapper);
        return ApiResult.success(page);
    }

    @GetMapping("/category/{id}")
    public ApiResult<Category> getData(@PathVariable("id") int id) {
        Category data = categoryService.getById(id);
        return data == null ? ApiResult.failed() : ApiResult.success(data);
    }

    @PostMapping("/category/")
    public ApiResult<String> insertData(@RequestBody Category data) {
        boolean flag = categoryService.save(data);
        return flag ? ApiResult.success() : ApiResult.failed();
    }

    @PutMapping("/category/")
    public ApiResult<String> updateData(@RequestBody Category category) {
        boolean flag = categoryService.updateById(category);
        return flag ? ApiResult.success() : ApiResult.failed();
    }

    @DeleteMapping("/category/list/")
    public ApiResult<String> deleteData(@RequestParam("ids") int[] ids) {
        List<Integer> collect = Arrays.stream(ids).boxed().collect(Collectors.toList());
        boolean flag = categoryService.removeByIds(collect);
        return flag ? ApiResult.success() : ApiResult.failed();
    }

    @GetMapping("/category/list/")
    public ApiResult<List<Category>> getCategoryList() {
        List<Category> list = categoryService.list();
        return ApiResult.success(list);
    }

}

